package pl.edu.agh.pros.proxy.logic.dao;

import java.util.ArrayList;
import java.util.Collection;

import pl.edu.agh.pros.proxy.logic.dao.common.AbstractDAO;
import pl.edu.agh.pros.proxy.logic.wrapper.AppConfigurationWrapper;
import pl.edu.agh.pros.proxy.model.AppConfiguration;
import pl.edu.agh.pros.proxy.model.XmppServerConfiguration;

import com.google.appengine.api.datastore.Key;

public class AppConfigurationDAO extends AbstractDAO<AppConfiguration> {

	private static final AppConfigurationDAO instance = new AppConfigurationDAO();

	private AppConfigurationDAO() {
		super(AppConfiguration.class);
	}

	public static AppConfigurationDAO getInstance() {
		return instance;
	}

	public Collection<AppConfigurationWrapper> getAppConfigurations(Key providerKey) {
		Collection<AppConfigurationWrapper> collection = new ArrayList<AppConfigurationWrapper>();
		Collection<AppConfiguration> original = this.getObjects("providerKey==param1", "Object param1", providerKey);
		if (original != null) {
			for (AppConfiguration ac : original) {
				collection.add(convertToVO(ac));
			}
		}
		return collection;
	}

	public void saveNewConfiguration(AppConfigurationWrapper configuration, Key providerKey) {
		configuration.setProviderKey(providerKey);
		this.save(convertFromVO(configuration));
	}

	public void updateConfiguration(AppConfigurationWrapper configuration) {
		this.save(convertFromVO(configuration));
	}

	public void deleteConfiguration(AppConfigurationWrapper selectedConfiguration) {
		this.deleteByKey(selectedConfiguration.getKey());
	}

	public XmppServerConfiguration getXmppServerConfiguration(String appKey) {
		AppConfiguration appConfiguration = getAppConfigurationByAppKey(appKey);
		if (appConfiguration == null) {
			return null;
		}
		return XmppServerConfigurationDAO.getInstance().getObject("key==param1", "Object param1",
				appConfiguration.getXmppServerConfigurationKey());

	}

	private AppConfiguration getAppConfigurationByAppKey(String appKey) {
		AppConfiguration appCfg = this.getObject("clientAppKey==param1", "String param1", appKey);
		if (appCfg == null) {
			appCfg = this.getObject("providerAppKey==param1", "String param1", appKey);
		}
		return appCfg;
	}

	private AppConfigurationWrapper convertToVO(AppConfiguration appConfiguration) {
		AppConfigurationWrapper appConfigurationVO = new AppConfigurationWrapper(appConfiguration);
		appConfigurationVO.setXmppServerConfiguration(XmppServerConfigurationDAO.getInstance().getObjectByKey(
				appConfiguration.getXmppServerConfigurationKey()));
		return appConfigurationVO;
	}

	private AppConfiguration convertFromVO(AppConfigurationWrapper appConfigurationVO) {
		return appConfigurationVO.getAppConfiguration();
	}

}
